<script lang="ts" setup>
import BaseButton from "@/components/BaseButton/index.vue";
import BaseUpDown from "@/components/BaseUpDown/index.vue";
import useSearch from "@/hooks/useSearch";
import useData from "./hooks/useData";
import { useUserStore } from "@/stores/modules/user";
import { formatDate } from "@/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref } from "vue";

const { pageData, agrMap } = useData();
import { getDataByPage, editData, editDataStatus } from "@/api/modules/resource/library";
import UpdateForm from "./components/UpdateForm/index.vue";
import moment from "moment";

const userStore = useUserStore();
const username = computed(() => userStore.userInfo.name);
const { tableData, loadData, formData, reloadData } = useSearch({
  defaultData: {
    pageSize: 50
  },
  responseKey: {
    list: "result.data",
    total: "result.total"
  }
});

function loadDataCb() {
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      pageNum: formData.pageNum - 1,
      pageSize: formData.pageSize,
      name: formData.name,
      pri: formData.pri
    }
  });
}

loadDataCb();

function reloadDataCb() {
  reloadData();
  formData.pageSize=50
  formData.pageNum=1
  loadData({
    api: getDataByPage,
    sendData: {
      curpage: formData.pageNum - 1,
      perpage: formData.pageSize,
      pageNum: formData.pageNum - 1,
      pageSize: formData.pageSize,
      name: formData.name,
      pri: formData.pri
    }
  });
}

loadDataCb();

/**删除*/
import useDelete from "@/hooks/useDelete";
import { computed } from "vue";
import BaseCollapse from "@/components/BaseCollapse/index.vue";
import { Upload } from "@element-plus/icons-vue";

const { deleteHandler, idList } = useDelete();

async function deleteCb(id) {
  await deleteHandler({
    api: deleteData,
    multiple: false,
    sendData: {
      id
    },
    hideMessageBox: false
  });
  loadDataCb();
}

function selectCb(data) {
  console.log(data);
  idList.value = data.rowList.map(item => item.userId);
}

const urlDownload = function (url, name) {
  var a = document.createElement("a");
  // console.log(url)
  a.setAttribute("href", url);
  a.setAttribute("download", name);
  a.setAttribute("target", "_blank");
  const clickEvent = document.createEvent("MouseEvents");
  clickEvent.initEvent("click", true, true);
  a.dispatchEvent(clickEvent);
};

async function templateOperate(type) {
  if (type === "export") {
    const res = await exportData();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "download") {
    const res = await downloadTemplate();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_template_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "import") {
    const tempInput = document.createElement("input");
    tempInput.type = "file";
    tempInput.accept = ".xls,.xlsx,.csv";
    tempInput.click();
    tempInput.addEventListener("change", async () => {
      const res = await importData({ file: tempInput.files[0] });
      if (res.success) {
        ElMessage.success("导入成功");
        loadDataCb();
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
  // this.waitOperator();
}

const ipprotoMap = new Map([
  ["ICMP", "1"],
  ["TCP", "6"],
  ["UDP", "17"]
]);
const priMap = new Map([
  ["高", "3"],
  ["中", "2"],
  ["低", "1"]
]);

async function operation(rowData, type) {
  await ElMessageBox.confirm(`确认${type == 1 ? "开启" : "关闭"}已选中的数据项?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "danger"
  });

  // let data = {
  //   ...rowData,
  //   name: rowData[1],
  //   state: type == 1 ? "0" : "1",
  //   dport: rowData[3],
  //   pri: priMap.get(rowData[4]),
  //   ipproto: ipprotoMap.get(rowData[2]),
  //   id: rowData[rowData.length - 1].replace("/", ""),
  //   description: ""
  // };
  // await editData(data);
  let data = {
    state: type == 1 ? "1" : "0",
    id: rowData[rowData.length - 1].replace("/", "")
  };
  await editDataStatus(data);
  ElMessage.success("操作成功");
  loadDataCb();
}

const selectIndex = ref("");
const selectValue = ref("");

const selectInput = ref(null);

function showSelectInput(index, value) {
  selectIndex.value = index;
  selectValue.value = value;
  setTimeout(() => {
    console.log(selectInput.value);
    selectInput.value.toggleMenu();
  }, 300);
}

function visibleChange(show) {
  console.log("show", show);
  if (!show) {
    selectIndex.value = -1;
  }
}

async function change(value, rowData) {
  console.log(value);
  let data = {
    ...rowData,
    name: rowData[1],
    state: rowData[6],
    dport: rowData[3],
    pri: priMap.get(value),
    ipproto: ipprotoMap.get(rowData[2]),
    id: rowData[rowData.length - 1].replace("/", ""),
    description: ""
  };
  await editData(data);
  selectIndex.value = -1;
  ElMessage.success("操作成功");
  loadDataCb();
}

function pageChange(data) {
  console.log(data);
  formData.pageNum = data;
  loadDataCb();
}
</script>

<template>
  <BaseUpDown>
    <template #up>
      <BaseCollapse title="">
        <el-form>
          <div class="h-box" style="flex-wrap: wrap">
            <el-form-item label="攻击类型">
              <el-input v-model="formData.name" placeholder="请输入" style="width: 120px" />
            </el-form-item>
            <el-form-item class="mg-l-sm" label="等级">
              <el-select v-model="formData.pri" style="width: 120px">
                <el-option value="3" label="高"></el-option>
                <el-option value="2" label="中"></el-option>
                <el-option value="1" label="低"></el-option>
              </el-select>
            </el-form-item>
            <BaseButton class="mg-l-sm" style="margin-bottom: 18px" @click="loadDataCb()" type="search_icon_text" />
            <BaseButton class="mg-l-sm" style="margin-bottom: 18px" @click="reloadDataCb()" type="reset_icon_text" />
          </div>
        </el-form>
      </BaseCollapse>
    </template>
    <div class="box">
      <div class="item h-box justify-center" v-for="(item, index) in tableData.list">
        <span>{{ item[1] }}</span>
        <div class="mg-l-sm">
          <el-select
            @visible-change="visibleChange"
            ref="selectInput"
            @change="v => change(v, tableData.list[index])"
            :class="`select${index}`"
            v-model="item[4]"
            style="width: 80px"
          >
            <el-option value="高" label="高"></el-option>
            <el-option value="中" label="中"></el-option>
            <el-option value="低" label="低"></el-option>
          </el-select>
          <!--          <template >-->
          <!--            <el-select-->
          <!--              @visible-change="visibleChange"-->
          <!--              ref="selectInput"-->
          <!--              @change="v => change(v, tableData.list[index])"-->
          <!--              :class="`select${index}`"-->
          <!--              v-model="selectValue"-->
          <!--              style="width: 80px"-->
          <!--            >-->
          <!--              <el-option value="高" label="高"></el-option>-->
          <!--              <el-option value="中" label="中"></el-option>-->
          <!--              <el-option value="低" label="低"></el-option>-->
          <!--            </el-select>-->
          <!--          </template>-->
          <!--          <div v-else class="h-box justify-center flex-align-center">-->
          <!--            <span>{{ item[4] }}</span>-->

          <!--            <span @click="showSelectInput(index, item[4])">-->
          <!--            <el-icon class="mg-l-sm" style="cursor: pointer"><Edit /></el-icon-->
          <!--            ></span>-->
          <!--          </div>-->
        </div>
      </div>
    </div>
    <div v-if="tableData.list?.length" class="h-box justify-end mg-t-sm">
      <el-pagination
        v-model:current-page="currentPage1"
        :page-size="formData.pageSize"
        layout="total, prev, pager, next"
        :total="tableData.total"
        @change="pageChange"
        @current-change="pageChange"
      />
    </div>

    <he-table
      v-if="false"
      @handle-current-change="loadDataCb"
      :total="tableData.total"
      v-model:page-size="formData.pageSize"
      v-model:page-num="formData.pageNum"
      operate-width="180px"
      :operate-list="[]"
      :table-data="tableData.list"
      :column-data="pageData.columnData"
      :show-multiple="false"
      :show-summary="false"
      :show-operate="false"
      :show-multiple-column="false"
      :show-pagination="true"
      @select="selectCb"
    >
      <template #operationDefault="{ data }">
        <el-switch @click="operation(data.row, data.row[6] == '0' ? 1 : 2)" :model-value="data.row[6] == '1'"></el-switch>
        <!--        <el-button @click="operation(data.row, 1)" v-if="data.row[6] == '0'" type="primary" link>开启</el-button>-->
        <!--        <el-button @click="operation(data.row, 2)" v-else type="primary" link>关闭</el-button>-->
      </template>
      <template #4Default="{ data }">
        <template v-if="selectIndex === data.$index">
          <el-select
            @visible-change="visibleChange"
            ref="selectInput"
            @change="v => change(v, data.row)"
            :class="`select${data.$index}`"
            v-model="selectValue"
            style="width: 80px"
          >
            <el-option value="高" label="高"></el-option>
            <el-option value="中" label="中"></el-option>
            <el-option value="低" label="低"></el-option>
          </el-select>
        </template>

        <div v-else class="h-box justify-center flex-align-center">
          <span>{{ data.row[4] }}</span>

          <span @click="showSelectInput(data.$index, data.row[4])">
            <el-icon class="mg-l-sm" style="cursor: pointer"><Edit /></el-icon
          ></span>
        </div>
      </template>
    </he-table>
  </BaseUpDown>
</template>
<style scoped lang="scss">
.box {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  gap: 0px;
  border: 0.5px solid #e6dddd;
  .item {
    border: 0.5px solid #e6dddd;
    padding: 10px;
  }
}
</style>
